const fs = require('fs');
const path = require('path');

/**
 * 批量禁用实体文件中的外键关系
 */
async function disableForeignKeys() {
  console.log('🔧 开始禁用实体文件中的外键关系...');
  
  const entitiesDir = path.join(__dirname, 'nestjs-app/src/entities');
  const casinoEntitiesDir = path.join(__dirname, 'nestjs-app/src/modules/casino/entities');
  
  const filesToProcess = [];
  
  // 收集所有实体文件
  function collectFiles(dir) {
    if (!fs.existsSync(dir)) return;
    
    const files = fs.readdirSync(dir);
    for (const file of files) {
      const filePath = path.join(dir, file);
      const stat = fs.statSync(filePath);
      
      if (stat.isDirectory()) {
        collectFiles(filePath);
      } else if (file.endsWith('.entity.ts')) {
        filesToProcess.push(filePath);
      }
    }
  }
  
  collectFiles(entitiesDir);
  collectFiles(casinoEntitiesDir);
  
  console.log(`📋 找到 ${filesToProcess.length} 个实体文件需要处理`);
  
  let processedCount = 0;
  let modifiedCount = 0;
  
  for (const filePath of filesToProcess) {
    try {
      const content = fs.readFileSync(filePath, 'utf8');
      let modified = false;
      let newContent = content;
      
      // 检查是否包含外键关系装饰器
      if (content.includes('@ManyToOne') || content.includes('@OneToMany') || content.includes('@OneToOne') || content.includes('@JoinColumn')) {
        console.log(`🔍 处理文件: ${path.relative(__dirname, filePath)}`);
        
        // 注释掉外键关系装饰器
        newContent = newContent.replace(/@ManyToOne\([^)]*\)/g, '// @ManyToOne');
        newContent = newContent.replace(/@OneToMany\([^)]*\)/g, '// @OneToMany');
        newContent = newContent.replace(/@OneToOne\([^)]*\)/g, '// @OneToOne');
        newContent = newContent.replace(/@JoinColumn\([^)]*\)/g, '// @JoinColumn');
        
        // 注释掉外键关系字段
        newContent = newContent.replace(/^\s*@ManyToOne\([^)]*\)\s*\n\s*@JoinColumn\([^)]*\)\s*\n\s*([^!]+)!: ([^;]+);/gm, '// $1!: $2;');
        newContent = newContent.replace(/^\s*@OneToMany\([^)]*\)\s*\n\s*([^!]+)!: ([^;]+);/gm, '// $1!: $2;');
        newContent = newContent.replace(/^\s*@OneToOne\([^)]*\)\s*\n\s*@JoinColumn\([^)]*\)\s*\n\s*([^!]+)!: ([^;]+);/gm, '// $1!: $2;');
        
        modified = true;
      }
      
      if (modified) {
        fs.writeFileSync(filePath, newContent, 'utf8');
        console.log(`✅ 已禁用外键关系: ${path.relative(__dirname, filePath)}`);
        modifiedCount++;
      }
      
      processedCount++;
    } catch (error) {
      console.error(`❌ 处理文件失败: ${path.relative(__dirname, filePath)}`, error.message);
    }
  }
  
  console.log(`\n📊 处理完成:`);
  console.log(`   总文件数: ${processedCount}`);
  console.log(`   修改文件数: ${modifiedCount}`);
  console.log(`   未修改文件数: ${processedCount - modifiedCount}`);
  
  if (modifiedCount > 0) {
    console.log('\n🎉 外键关系禁用完成！现在可以启动应用了。');
  } else {
    console.log('\nℹ️ 没有找到需要修改的文件。');
  }
}

// 执行禁用
disableForeignKeys()
  .then(() => {
    console.log('✅ 外键关系禁用脚本执行完成');
    process.exit(0);
  })
  .catch((error) => {
    console.error('💥 外键关系禁用脚本执行失败:', error.message);
    process.exit(1);
  });
